dojo.provide("lorelei.require");

// Lorelei Script Loader
// Copyright (c)2008 Logue <http://logue.be/> All rights reserved.

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

lorelei.require.meta = {
	"@prefix": "<http://purl.org/net/ns/doas#>",
	"@about": "<http://mabinogi.logue.be/js/lolerei/setClipboard.js>", a: ":JavaScript",
	 title: "Lorelei Script Loader",
	 shortdesc: "dojo.require IE fix. if dojo.require failure, try to load script tag.",
	 created: "2008-06-10", release: {revision: "1.2.1", created: "2008-09-03"},
	 author: {name: "Logue", homepage: "<http://logue.be/>"},
	 license: "<http://www.gnu.org/licenses/gpl-3.0.html>"
};

console.log(lorelei.require.meta.title,lorelei.require.meta.release,' has been loaded!');

lorelei.require = function(script){
	try{
		console.info('Try require by dojo.require. If no error in IE, it is not necessary to use lorelei.require.');
		// dojo.requireを用いてスクリプトを呼び出す。
		dojo.require(script);
	}catch(e){
		// dojo.requireでスクリプトが呼び出せなかった場合
		var url = '/js/' + script.replace(/\./g,'/')+'.js';
		dojo.addOnLoad(function (){
			var scriptTag = document.createElement('script');
			scriptTag.id = script;
			scriptTag.type = 'text/javascript';
			scriptTag.defer = true;
			try{
				console.info('Require by head script tag.(External file)');
				// Headタグに<script>タグを用いてスクリプトを呼び出す。
				scriptTag.src  = url;
				document.getElementsByTagName('head').item(0).appendChild(scriptTag);
			}catch(e){
				// スクリプトの内容をそのままXHRを用いてページに埋め込む。
				console.info('Try require by body script tag.(Page Internal Script)');
				dojo.xhrGet({
					url: url,
					handleAs: "text",
					timeout: 5000, // Time in milliseconds
					// The LOAD function will be called on a successful response.
					handle: function(response, ioArgs) {
						console.log("dojo.xhrGet: Success!",ioArgs);
						scriptTag.text = response;
						dojo.body().appendChild(scriptTag);
						return response;
					},
					error: function(response, ioArgs) { 
						console.error("dojo.xhrGet: Failure");
						console.log("Responce: "+responce);
						console.log("HTTP status code: ", ioArgs.xhr.status);
						return response;
					}
				});
			}
			console.log("Script Tag ",scriptTag);
		});
	}
};
